from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from django.db.models import Q
from .models import Product
from .serializers import ProductSerializer
from warehouse_system.pagination import StandardResultsSetPagination


class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = StandardResultsSetPagination

    def get_permissions(self):
        if self.action in ['destroy', 'status']:
            return [IsAdminUser()]
        return [IsAuthenticated()]

    def get_queryset(self):
        queryset = super().get_queryset()
        name = self.request.query_params.get('name')
        if name:
            queryset = queryset.filter(
                Q(name__icontains=name) |
                Q(code__icontains=name)
            )
        return queryset

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)

        # 获取新创建的产品对象
        product = serializer.instance

        # 使用 ProductSerializer 序列化产品对象
        product_data = ProductSerializer(product).data

        # 构建自定义响应格式
        response_data = {
            "code": 1,
            "data": {
                "id": product_data['id'],
                "name": product_data['name'],
                "code": product_data['code'],
                "unit": product_data['unit'],
                "purchase_price": product_data['purchase_price'],
                "sale_price": product_data['sale_price'],
                "stock": product_data['stock'],
                "warning_stock": product_data['warning_stock'],
                "status": product_data['status'],
                "create_time": product_data['create_time'],
                "update_time": product_data['update_time']
            }
        }

        headers = self.get_success_headers(serializer.data)
        return Response(response_data, status=status.HTTP_201_CREATED, headers=headers)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()

        try:
            from stock.models import StockInDetail, StockOutDetail

            # 删除与该产品关联的所有出入库明细
            StockInDetail.objects.filter(product=instance).delete()
            StockOutDetail.objects.filter(product=instance).delete()

            # 再删除产品
            self.perform_destroy(instance)

            response_data = {
                "code": 1,
                "data": None
            }
            return Response(response_data, status=status.HTTP_200_OK)

        except Exception as e:
            return Response({
                "code": 0,
                "msg": f"删除失败：{str(e)}"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=True, methods=['post'])
    def status(self, request, pk=None):
        status = request.data.get('status')
        if status not in [0, 1]:
            return Response({'code': 0, 'msg': '状态值无效'}, status=status.HTTP_400_BAD_REQUEST)

        product = self.get_object()
        product.status = status
        product.save()
        return Response({'code': 1, 'data': None})

    @action(detail=True, methods=['put'])
    def stock(self, request, pk=None):
        stock = request.data.get('stock')
        if not isinstance(stock, int) or stock < 0:
            return Response({'code': 0, 'msg': '库存数量无效'}, status=status.HTTP_400_BAD_REQUEST)

        product = self.get_object()
        product.stock = stock
        product.save()
        return Response({'code': 1, 'data': None})
